package com.brainwave;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.brainwave.ui.adapters.MainPagerAdapter;
import com.brainwave.ui.fragments.DashboardFragment;
import com.brainwave.ui.fragments.RealtimeFragment;
import com.brainwave.ui.fragments.HistoryFragment;
import com.brainwave.ui.fragments.SettingsFragment;
import com.brainwave.utils.Logger;
import com.brainwave.utils.PermissionManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

/**
 * 主活动 - 应用程序的入口点
 * 负责权限管理、导航控制和基础UI框架
 */
public class MainActivity extends AppCompatActivity {
    
    private static final String TAG = "MainActivity";
    private static final int PERMISSION_REQUEST_CODE = 1001;
    
    // UI 组件
    private ViewPager2 viewPager;
    private TabLayout tabLayout;
    private BottomNavigationView bottomNavigation;
    private MainPagerAdapter pagerAdapter;
    
    // 权限管理
    private PermissionManager permissionManager;
    
    // 必需权限列表
    private final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    
    // Android 12+ 蓝牙权限
    private final String[] BLUETOOTH_PERMISSIONS_API31 = {
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_SCAN
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 初始化日志系统
        initializeLogging();
        
        // 初始化权限管理器
        permissionManager = new PermissionManager(this);
        
        // 初始化UI组件
        initializeViews();
        
        // 设置ViewPager和Fragment
        setupViewPager();
        
        // 检查并请求权限
        checkAndRequestPermissions();
        
        Timber.tag(TAG).d("MainActivity created successfully");
    }
    
    /**
     * 初始化日志系统
     */
    private void initializeLogging() {
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        Logger.init(this);
    }
    
    /**
     * 初始化UI组件
     */
    private void initializeViews() {
        viewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tabLayout);
        bottomNavigation = findViewById(R.id.bottomNavigation);
        
        // 设置ViewPager滑动行为
        viewPager.setUserInputEnabled(true);
        viewPager.setOffscreenPageLimit(3);
    }
    
    /**
     * 设置ViewPager和Fragment
     */
    private void setupViewPager() {
        List<Fragment> fragments = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        
        // 添加Fragment
        fragments.add(new DashboardFragment());
        titles.add(getString(R.string.tab_dashboard));
        
        fragments.add(new RealtimeFragment());
        titles.add(getString(R.string.tab_realtime));
        
        fragments.add(new HistoryFragment());
        titles.add(getString(R.string.tab_history));
        
        fragments.add(new SettingsFragment());
        titles.add(getString(R.string.tab_settings));
        
        // 创建适配器
        pagerAdapter = new MainPagerAdapter(this, fragments);
        viewPager.setAdapter(pagerAdapter);
        
        // 连接TabLayout和ViewPager2
        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> tab.setText(titles.get(position))
        ).attach();
        
        // 设置底部导航
        setupBottomNavigation();
    }
    
    /**
     * 设置底部导航
     */
    private void setupBottomNavigation() {
        bottomNavigation.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_dashboard) {
                viewPager.setCurrentItem(0, true);
                return true;
            } else if (itemId == R.id.nav_realtime) {
                viewPager.setCurrentItem(1, true);
                return true;
            } else if (itemId == R.id.nav_history) {
                viewPager.setCurrentItem(2, true);
                return true;
            } else if (itemId == R.id.nav_settings) {
                viewPager.setCurrentItem(3, true);
                return true;
            }
            return false;
        });
        
        // 同步ViewPager和底部导航
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switch (position) {
                    case 0:
                        bottomNavigation.setSelectedItemId(R.id.nav_dashboard);
                        break;
                    case 1:
                        bottomNavigation.setSelectedItemId(R.id.nav_realtime);
                        break;
                    case 2:
                        bottomNavigation.setSelectedItemId(R.id.nav_history);
                        break;
                    case 3:
                        bottomNavigation.setSelectedItemId(R.id.nav_settings);
                        break;
                }
            }
        });
    }
    
    /**
     * 检查并请求权限
     */
    private void checkAndRequestPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();
        
        // 检查基础权限
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }
        
        // 检查Android 12+蓝牙权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            for (String permission : BLUETOOTH_PERMISSIONS_API31) {
                if (ContextCompat.checkSelfPermission(this, permission) 
                        != PackageManager.PERMISSION_GRANTED) {
                    permissionsToRequest.add(permission);
                }
            }
        }
        
        // 请求权限
        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    permissionsToRequest.toArray(new String[0]),
                    PERMISSION_REQUEST_CODE);
        } else {
            onPermissionsGranted();
        }
    }
    
    /**
     * 权限请求结果处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            List<String> deniedPermissions = new ArrayList<>();
            
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    deniedPermissions.add(permissions[i]);
                }
            }
            
            if (allPermissionsGranted) {
                onPermissionsGranted();
            } else {
                onPermissionsDenied(deniedPermissions);
            }
        }
    }
    
    /**
     * 权限授予后的处理
     */
    private void onPermissionsGranted() {
        Timber.tag(TAG).d("All permissions granted");
        Toast.makeText(this, R.string.permissions_granted, Toast.LENGTH_SHORT).show();
        
        // 初始化需要权限的组件
        initializeBluetoothComponents();
        initializeNetworkComponents();
    }
    
    /**
     * 权限被拒绝后的处理
     */
    private void onPermissionsDenied(List<String> deniedPermissions) {
        Timber.tag(TAG).w("Permissions denied: %s", deniedPermissions.toString());
        
        StringBuilder message = new StringBuilder(getString(R.string.permissions_denied));
        for (String permission : deniedPermissions) {
            message.append("\n- ").append(getPermissionName(permission));
        }
        
        Toast.makeText(this, message.toString(), Toast.LENGTH_LONG).show();
        
        // 显示权限说明对话框
        permissionManager.showPermissionRationaleDialog(deniedPermissions);
    }
    
    /**
     * 获取权限的友好名称
     */
    private String getPermissionName(String permission) {
        switch (permission) {
            case Manifest.permission.BLUETOOTH:
            case Manifest.permission.BLUETOOTH_ADMIN:
            case Manifest.permission.BLUETOOTH_CONNECT:
            case Manifest.permission.BLUETOOTH_SCAN:
                return getString(R.string.permission_bluetooth);
            case Manifest.permission.ACCESS_COARSE_LOCATION:
            case Manifest.permission.ACCESS_FINE_LOCATION:
                return getString(R.string.permission_location);
            case Manifest.permission.INTERNET:
            case Manifest.permission.ACCESS_NETWORK_STATE:
                return getString(R.string.permission_network);
            case Manifest.permission.READ_EXTERNAL_STORAGE:
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                return getString(R.string.permission_storage);
            default:
                return permission;
        }
    }
    
    /**
     * 初始化蓝牙组件
     */
    private void initializeBluetoothComponents() {
        // TODO: 在第二步实现蓝牙模块时添加初始化代码
        Timber.tag(TAG).d("Bluetooth components initialization placeholder");
    }
    
    /**
     * 初始化网络组件
     */
    private void initializeNetworkComponents() {
        // TODO: 在第四步实现网络模块时添加初始化代码
        Timber.tag(TAG).d("Network components initialization placeholder");
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Timber.tag(TAG).d("MainActivity resumed");
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Timber.tag(TAG).d("MainActivity paused");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Timber.tag(TAG).d("MainActivity destroyed");
    }
}